/*
 * Copyright (c) 2010 Oracle
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

package ritcs.sensors.app;

import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.peripheral.ota.OTACommandServer;
import com.sun.spot.peripheral.radio.BasestationManager;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.*;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

/**
 * Simple example class to listen for a remote service (on a SPOT) and
 * to connect to it.
 *
 * @author Ron Goldman<br>
 * Date: August 1, 2010
 */
public class SpotListener extends Thread implements PacketTypes {

    public static ImageIcon aboutIcon = null;

    private static JFrame fr;
    private static Vector windows = new Vector();

    private static boolean baseStationPresent = false;
    private static RadiogramConnection rcConn = null;
    private static DatagramConnection txConn = null;
    private static Datagram txDg;
    private static Database dbHandler;

    private static JTextArea status;
    private static long[] addresses = new long[20];
   
    /**
     * Create a new SpotListener to connect to remote SPOTs over the radio.
     */
    public SpotListener () {
    }

    /**
     * Connect to base station & other initialization.
     */
    private void init () {
        baseStationPresent = true;              // assume we have a basestation
        boolean dedicatedBasestation = true;
        String tmp = System.getProperty("spot.basestation.sharing");
        if (tmp != null && "true".equalsIgnoreCase(tmp)) {  // using shared basestation
            dedicatedBasestation = false;
        } else {
            tmp = System.getProperty("SERIAL_PORT");        // does serial port = dummyport ?
            dedicatedBasestation = tmp != null && !"dummyport".equalsIgnoreCase(tmp);
        }
        if (!dedicatedBasestation) {
            baseStationPresent = BasestationManager.isSharedBasestationPresent();
        }
        if (!baseStationPresent) {
            status.append("No base station connected.\n");
	}
	try {
            rcConn = (RadiogramConnection) Connector.open("radiogram://:" + BROADCAST_PORT);
            txConn = (DatagramConnection) Connector.open("radiogram://broadcast:" + CONNECTED_PORT);
            ((RadiogramConnection) txConn).setMaxBroadcastHops(4);
            txDg = txConn.newDatagram(10);
            baseStationPresent = true;
        } catch (Exception ex) {
            baseStationPresent = false;
            status.append("Problem connecting to base station: " + ex + "\n");
        }
    }
    

    /**
     * Main runtime loop to connect to a remote SPOT.
     * Do not call directly. Call start() instead.
     */
    public void run () {
        if (baseStationPresent) {
            broadcastCmd(DISPLAY_SERVER_RESTART); // Broadcast that the host display server is starting
//            status.append("Listening for SPOTs...\n");
            listenForSpots();
        } else {
            while (true) {
                Utils.sleep(10000);
            }
        }
    }

    /**
     * Broadcast a simple command request to the remote SPOTs.
     *
     * @param cmd the command to send
     */
    private static void broadcastCmd (byte cmd) {
        if (baseStationPresent) {
            try {
                txDg.reset();
                txDg.writeByte(cmd);
                txConn.send(txDg);
            } catch (IOException ex) {
                status.append("Error broadcasting server start/quit command: " + ex.toString() + "\n");
            }
        }
    }

    /**
     * Stop running. Also notify the remote SPOTs that we are no longer listening to them.
     */
    public static void doQuit () {
        broadcastCmd(DISPLAY_SERVER_QUITTING);
        System.exit(0);
    }

    
    /**
     * Wait for a remote SPOT to request a connection.
     */
    private void listenForSpots () {
        while (true) {
            try {
                Datagram dg = rcConn.newDatagram(10);
                rcConn.receive(dg);            // wait until we receive a request
                if (dg.readByte() == LOCATE_DISPLAY_SERVER_REQ) {       // type of packet
                    String addr = dg.getAddress();
                    IEEEAddress ieeeAddr = new IEEEAddress(addr);
                    long macAddress = ieeeAddr.asLong();
                    System.out.println("Received request from: " + ieeeAddr.asDottedHex());
                    Datagram rdg = rcConn.newDatagram(10);
                    rdg.reset();
                    rdg.setAddress(dg);
                    rdg.writeByte(DISPLAY_SERVER_AVAIL_REPLY);        // packet type
                    rdg.writeLong(macAddress);                        // requestor's ID
                    rcConn.send(rdg);                                // send it
                    //findFrame(macAddress);
                    this.dbHandler = new Database(IEEEAddress.toDottedHex(macAddress));
                    Listener listener = new Listener(IEEEAddress.toDottedHex(macAddress),dbHandler);
                    listener.start();
                    Thread.sleep(2000);

                    
                    
                    System.out.println("Blink");
                    listener.doPing();
                    listener.getTemperature(3);

                    listener.getGUIParams();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(SpotListener.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                System.out.println("Error waiting for remote Spot: " + ex.toString());
                ex.printStackTrace();
            }
        }
    }

    private void setup() {
        
       // initMenus();
        init();
        //addFrame(fr);
    }

    /**
     * Start up the host application.
     *
     * @param args any command line arguments
     */
    public static void main(String[] args) throws Exception {
        // Set system properties for Mac OS X before AWT & Swing get loaded - doesn't hurt if not on a MAC
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("com.apple.mrj.application.apple.menu.about.name", "TelemetryDemo");

        // register the application's name with the OTA Command server & start OTA running
        OTACommandServer.start("TelemetryDemo");

        SpotListener us = new SpotListener();
        us.setup();
       us.start();
      //  ApplicationWindow us = new ApplicationWindow("Chimbs Rocls");
        //us.setVisible(true);
    }

}
